/**
 * Main UI
 * @author William
 * 2012-1-14
 */

package com.ytu.irss;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class IRSSActivity extends Activity implements OnItemClickListener {

	SharedPreferences urls;
	private ProgressDialog p;
	private static String RSS_URL;
	private Spinner spinner;

	// "http://forum.csdn.net/Rss/VC/UnClosedList/";//"http://articles.csdn.net/api/rss.php?tid=1008";
	// "http://forum.csdn.net/Rss/Java/UnClosedList/";//"http://forum.csdn.net/Rss/Android/UnClosedList/";
	// "http://www.ibm.com/developerworks/views/rss/customrssatom.jsp?zone_by=XML&zone_by=Java&zone_by=Rational&zone_by=Linux&zone_by=Open+source&zone_by=WebSphere&type_by=Tutorials&search_by=&day=1&month=06&year=2007&max_entries=20&feed_by=rss&isGUI=true&Submit.x=48&Submit.y=14";
	public final String tag = "RSSReader";
	private RSSFeed feed = null;

	private EditText etName;
	private EditText etURL;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		urls = getSharedPreferences("test", 0);
//		if (!urls.contains("default"))// 如果没有包含默认，则添加
//			urls.edit()
//					.putString("dafualt",
//							"http://www.eoeandroid.com/forum.php?mod=rss&fid=132&auth=0")
//					.commit();

//		RSS_URL = urls
//				// 先使RSS_URL为默认值
//				.getString(
//						"default",
//						"http://www.ibm.com/developerworks/views/rss/customrssatom.jsp?zone_by=XML&zone_by=Java&zone_by=Rational&zone_by=Linux&zone_by=Open+source&zone_by=WebSphere&type_by=Tutorials&search_by=&day=1&month=06&year=2007&max_entries=20&feed_by=rss&isGUI=true&Submit.x=48&Submit.y=14");
		setSelect();
		showListView();
	}

	// spinner 条的内容设置
	public void setSelect() {
		spinner = (Spinner) findViewById(R.id.selectfeeds);
		refreshSpinner();
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				String keyStr = (String) spinner.getItemAtPosition(arg2);
				Toast.makeText(IRSSActivity.this, keyStr, 3).show();// keyStr
				RSS_URL = urls.getString(keyStr,null);
				showListView();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}

		});
	}

	protected void refreshSpinner() {
		List<String> list = new ArrayList<String>();
		Map<String, ?> maps = urls.getAll();
		Set<String> set = maps.keySet();
		list.addAll(set);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				R.layout.items, R.id.textViewId, list);
	  spinner.setAdapter(adapter);
	}

	public RSSFeed getFeed(String urlString) {
		try {
			URL url = new URL(urlString);

			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			XMLReader xmlReader = parser.getXMLReader();

			IRSSHandler rssHandler = new IRSSHandler();
			xmlReader.setContentHandler(rssHandler);

			InputSource is = new InputSource(url.openStream());
			xmlReader.parse(is);

			return rssHandler.getFeed();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void showListView() {
		TextView feedTitle = (TextView) findViewById(R.id.feedTitle);
		ListView itemList = (ListView) findViewById(R.id.itemList);

//		p = ProgressDialog.show(IRSSActivity.this, "loading...",
//				"Please wait...", true);
//		new Thread() {
//			public void run() {
//				try {
//					feed = getFeed(RSS_URL);
//				} catch (Exception e) {
//					e.printStackTrace();
//				} finally {
//					p.dismiss();// 登录结束后，取消对话框
//				}
//			}
//		}.start();

		feed = getFeed(RSS_URL);
		if (feed == null) {
			feedTitle.setText("RSS源无效!");
			itemList.setAdapter(null);
			return;
		}
		if (feed.getTitle() == null && feed.getPubDate() == null) {
			feedTitle.setText("iRSS");
		} else {
			feedTitle.setText(feed.getTitle());
		}
		feedTitle.setText(feed.getTitle());

		@SuppressWarnings("unchecked")
		SimpleAdapter adapter = new SimpleAdapter(this,
				feed.getAllItemsForListView(),
				android.R.layout.simple_list_item_2, new String[] {
						RSSItem.TITLE, RSSItem.PUBDATE }, new int[] {
						android.R.id.text1, android.R.id.text2 });
		itemList.setAdapter(adapter);
		itemList.setOnItemClickListener(this);
		itemList.setSelection(0);
	}

	public boolean storageFeedURL(String key, String url) {

		if (urls.contains(key))
			return false;
		else
			urls.edit().putString(key, url).commit();
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent itemIntent = new Intent(this, ShowDetailsActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("title", feed.getItem(arg2).getTitle());
		bundle.putString("description", feed.getItem(arg2).getDescription());
		bundle.putString("link", feed.getItem(arg2).getLink());
		bundle.putString("pubDate", feed.getItem(arg2).getPubDate());
		itemIntent.putExtra("rssItem", bundle);
		startActivityForResult(itemIntent, 0);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 1, 0, "New").setIcon(android.R.drawable.ic_menu_add);
		menu.add(0, 2, 0, "Quit").setIcon(
				android.R.drawable.ic_menu_close_clear_cancel);
		menu.add(0, 3, 0, "Refresh").setIcon(android.R.drawable.ic_menu_view);
		menu.add(0, 4, 0, "Select").setIcon(android.R.drawable.ic_menu_more);
		return true;
	}

	/* Handles item selections */

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			// Dialog show
			buildAddDialog(this).show();
			return true;
		case 2:
			finish();
			return true;
		case 3:
			// showListView();
			return true;
		case 4:
			// selectFeed();
			return true;
		}
		return false;
	}

	protected Dialog buildAddDialog(Context context) {
		LayoutInflater in = LayoutInflater.from(this);
		final View textEntryView = in.inflate(R.layout.addview, null);

		Builder dlgBld = new AlertDialog.Builder(context);
		dlgBld.setIcon(android.R.drawable.alert_light_frame);
		dlgBld.setTitle("Add Dialog");
		dlgBld.setView(textEntryView);

		OnClickListener yes_listener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				etName = (EditText) textEntryView.findViewById(R.id.feedName);
				etURL = (EditText) textEntryView.findViewById(R.id.feedURL);
				Editor editor = urls.edit();
				editor.putString(etName.getText().toString().trim(),
						etURL.getText().toString().trim()).commit();
				refreshSpinner();
			}
		};
		dlgBld.setPositiveButton("OK", yes_listener);

		OnClickListener no_listener = new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		};
		dlgBld.setNegativeButton("Cancel", no_listener);
		return dlgBld.create();
	}
}